package com.yh.csx.bsf.flow.engine.api;

import com.yh.csx.bsf.core.util.StringUtils;
import com.yh.csx.bsf.flow.core.base.ChooseUser;
import com.yh.csx.bsf.flow.core.base.Variable;
import com.yh.csx.bsf.flow.core.db.ConvertUtil;
import com.yh.csx.bsf.flow.core.db.DbHelper;
import com.yh.csx.bsf.flow.dao.dal.t_department_dal;
import com.yh.csx.bsf.flow.dao.dal.t_department_user_dal;
import com.yh.csx.bsf.flow.dao.dal.t_user_dal;
import com.yh.csx.bsf.flow.dao.model.auto.t_user_model;
import com.yh.csx.bsf.flow.engine.state.StateEngineException;

import lombok.*;
import org.apache.commons.lang.ArrayUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author: chejiangyi
 * @version: 2019-10-24 18:13
 **/
public class UserApi {
	
    public static List<String> getUserNos(int flowid,int taskid,Map<String,Variable> variables, List<ChooseUser> chooseUsers){
        List<String> userno= new ArrayList<>();
        for(var user:chooseUsers){
            List<String> users = new ArrayList<>();
            if(ChooseUser.UserRoleEnum.User.equals(user.getUserRoleEnum()))
            {
                users = getUsers(user);
            }
            else if(ChooseUser.UserRoleEnum.Variable.equals(user.getUserRoleEnum()))
            {
                users = getVariables(flowid,variables,user);
            }
            else if(ChooseUser.UserRoleEnum.Method.equals(user.getUserRoleEnum())){
                users = Arrays.asList(Api.run(flowid,taskid,user.getValue(),variables).split(","));
            }
            if(user.getSetOperationEnum()==null||ChooseUser.SetOperationEnum.Union.equals(user.getSetOperationEnum())){
                userno.addAll(users);
            } else if(ChooseUser.SetOperationEnum.Difference.equals(user.getSetOperationEnum())){
                userno.removeAll(users);
            }else if(ChooseUser.SetOperationEnum.Intersect.equals(user.getSetOperationEnum())){
                userno.retainAll(users);
            }else{

            }
            userno=filterUser(userno);
            userno = userno.stream().distinct().collect(Collectors.toList());
        }

        return userno;
    }

    /**
     * 	批量获取用户工号
     * @return
     */
    public static List<String> getUsers(ChooseUser chooseUser){
    	List<String> usernoList=new ArrayList<String>();
        usernoList.add(chooseUser.getValue());
        return usernoList;
    }


    /**
     * 	批量根据变量获取用户的工号
     * @return
     */
    public static List<String> getVariables(int flowid,Map<String,Variable> variables,ChooseUser chooseUser){
        val rs = new ArrayList<String>();
        	Variable variable = variables.get(chooseUser.getValue());
            if(variable ==null){
                throw new StateEngineException(flowid,"根据变量:"+chooseUser.getValue()+",查找用户失败,变量不存在");
            }
            rs.addAll(Arrays.asList(variable.getValue().split(",")));

        return rs;
    }

    /**
     * 对用户工号进行过滤不存在的工号
     * @param userno
     * @return
     */
    public static List<String> filterUser(List<String> userno){
        if(userno==null||userno.size()==0)
            return new ArrayList<>();
        val userno2 = userno.stream().filter(c->!StringUtils.isEmpty(c)).collect(Collectors.toList());
        if(userno2.size()==0)
            return userno2;
        return DbHelper.get((c) -> {
            return new t_user_dal().filterNos(c, userno2);
        });
    }

    /**
     * 获取用户信息
     * @param no
     * @return
     */
    public static t_user_model getUser(String no){
        return DbHelper.get((c)->{
            return new t_user_dal().getByNo(c,no);
        });
    }

    //根据用户工号获取n级用户集
    public static List<String> getByParentDepartment(int flowid,String orgName,String no,int level){
        return DbHelper.get((c)->{
            var rs = new ArrayList<String>();
            val d = new t_department_dal().getFirstDepartment(c,orgName);
            if(d==null){
                throw new StateEngineException(flowid,"组织:"+ StringUtils.nullToEmpty(orgName)+"不存在");
            }
            var u = new t_user_dal().getByNo(c,no);
            if(u == null){
                throw new StateEngineException(flowid,"用户:"+ StringUtils.nullToEmpty(no)+"不存在");
            }
            var dempartment_users = new t_department_user_dal().getListByFirstDepartment(c,d.getFirst_par_id(),u.id);
            if(dempartment_users.size()==0){
                return rs;
            }
            var dempartmentIds = dempartment_users.stream().map(o->o.getDepartment_id()).collect(Collectors.toList());
            var departments = new t_department_dal().list(c,dempartmentIds);
            if(departments.size()==0){
                return rs;
            }
            var departmentsParPaths = departments.stream().map(o->o.getPar_path()).collect(Collectors.toList());
            var levels = departments.stream().map(o->o.getLevel()).collect(Collectors.toList());
            var levelDepartmentIds = new ArrayList<Integer>();
            //向上
            if(level<0) {
                var level2 = Math.abs(level);
                for (var par_path : departmentsParPaths) {
                    var ids = par_path.split(",");
                    ArrayUtils.reverse(ids);
                    if (ids.length >= level2) {
                        levelDepartmentIds.add(ConvertUtil.strToInt(ids[level2-1]));
                    }
                }
            }
            //向下
            if(level>0){
                levels = levels.stream().map(o->o+level).collect(Collectors.toList());
                val nextDepartment = new t_department_dal().listByParPath(c,departmentsParPaths,levels);
                for(var n:nextDepartment){
                    levelDepartmentIds.add(n.id);
                }
            }
            if(levelDepartmentIds.size()==0){
                return rs;
            }
            var users = new t_department_user_dal().getListByDepartment(c,levelDepartmentIds);
            return users.stream().map(o->o.user_id+"").distinct().collect(Collectors.toList());
        });
    }

    //根据多个部门获取用户集
    public static List<String> getByDepartment(int flowid,String orgName,String name){
        return DbHelper.get((c)->{
            var rs = new ArrayList<String>();
            var d = new t_department_dal().getFirstDepartment(c,orgName);
            if(d==null){
                throw new StateEngineException(flowid,"组织:"+ StringUtils.nullToEmpty(orgName)+"不存在");
            }
            d = new t_department_dal().getDepartment(c,d.id,name);
            var users = new t_department_user_dal().getListByDepartment(c,Arrays.asList(d.id));
            return users.stream().map(o->o.user_id+"").distinct().collect(Collectors.toList());
        });
    }
    //根据多个用户工号获取用户集

}
